import cv2 as cv
import os
import sys
from PyCmpltrtok.common import IMG_FORMATS


class UpSampleException(Exception):
    pass


def up_sample(img, xn):
    if not isinstance(xn, int):
        raise UpSampleException(f"xn = {xn} must be integer.")
    H, W = img.shape[:2]

    dst = cv.resize(img, [W * xn, H * xn], interpolation=cv.INTER_CUBIC)
    return dst


def up_smaple_dir(src_dir, dst_dir, xn):
    xnames = os.listdir(src_dir)
    for xname in xnames:
        ext = os.path.splitext(xname)[1]
        if ext and ext[1:] not in IMG_FORMATS:
            print(f'{xname} is not a image file.')
            continue
        dst_path = os.path.join(dst_dir, xname)
        if os.path.exists(dst_path):
            print(f'Warning: {dst_path} existed!', file=sys.stderr)
            continue
        src_path = os.path.join(src_dir, xname)
        img = cv.imread(src_path, cv.IMREAD_UNCHANGED)
        dst = up_sample(img, xn)
        cv.imwrite(dst_path, dst)
        print(f'Written: {dst_path}')


if '__main__' == __name__:
    src_dir = '/home/asuspei/my_src/nerfies.git/data/curls/rgb/4x'
    dst_dir = '/home/asuspei/my_src/nerfies.git/data/curls_images'
    xn = 4
    up_smaple_dir(src_dir, dst_dir, xn)
